﻿using famails.bus;
using famails.common;
using famails.dto;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.BackEnd.page
{
    public partial class CreateContentMail : System.Web.UI.Page
    {
        SendContentBUS scBUS = null;
        DataTable SignIn = null;
        SignatureBUS signBus = null;
        log4net.ILog logs = log4net.LogManager.GetLogger("ErrorRollingLogFileAppender");
        UserLoginDTO userLogin = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                userLogin = getUserLogin();
                if (!IsPostBack)
                {
                    LoadContentMail();
                    LoadSignatureList();

                    int id = 0;
                    int.TryParse(Request.QueryString["id"], out id);
                    if (id > 0)
                        hdfContentId.Value = id + "";
                }

            }
            catch (Exception ex)
            {
                common.Common.logs(userLogin.Username+" - CreateContentMail - Load",ex, Common.logType.error);
            }
        }


        private void LoadSignatureList()
        {
            try
            {
                InitialBUS();
                signBus = new SignatureBUS();
                UserLoginDTO userLogin = getUserLogin();
                DataTable tblSignList = signBus.GetByUserId(userLogin.UserId);
                createTableSign();
                if (tblSignList.Rows.Count > 0)
                {
                    DataRow rowE = SignIn.NewRow();
                    rowE["Id"] = 0;
                    rowE["SignatureName"] = "Chọn chữ ký";
                    SignIn.Rows.Add(rowE);
                    foreach (DataRow RowItem in tblSignList.Rows)
                    {
                        rowE = SignIn.NewRow();
                        rowE["Id"] = RowItem["id"];
                        rowE["SignatureName"] = RowItem["SignatureName"];
                        SignIn.Rows.Add(rowE);
                    }
                    drlSign.DataSource = SignIn;
                    drlSign.DataTextField = "SignatureName";
                    drlSign.DataValueField = "id";
                    drlSign.DataBind();
                }
            }
            catch (Exception)
            {
            }
        }

        private void createTableSign()
        {
            SignIn = new DataTable("SignIn");
            DataColumn Id = new DataColumn("Id");
            Id.DataType = System.Type.GetType("System.Int32");
            DataColumn SignatureName = new DataColumn("SignatureName");
            DataColumn[] key = { Id };
            SignIn.Columns.Add(Id);
            SignIn.Columns.Add(SignatureName);
            SignIn.PrimaryKey = key;
        }


        private void LoadContentMail()
        {
            InitialBUS();
            try
            {
                int ID = int.Parse(Request.QueryString["id"].ToString());
                this.hdfContentId.Value = ID.ToString();
                if (ID != 0)
                {
                    if (scBUS.GetByID(ID).Rows.Count > 0)
                    {

                        this.txtSubject.Text = scBUS.GetByID(ID).Rows[0]["Subject"].ToString();
                        this.txtBody.Text = scBUS.GetByID(ID).Rows[0]["Body"].ToString();
                    }
                    else
                    {
                        pnError.Visible = true;
                        lblError.Text = "Không có nội dung ";
                        pnSuccess.Visible = false;
                    }
                }


            }
            catch (Exception ex)
            {

                //pnError.Visible = true;
                //lblError.Text = ex.ToString();
            }
        }

        private void InitialBUS()
        {
            scBUS = new SendContentBUS();
            signBus = new SignatureBUS();
        }
        protected void btnSaveContent_Click(object sender, EventArgs e)
        {
            try{
            pnError.Visible = pnSuccess.Visible = false;
            InitialBUS();
            int id = 0;
            int.TryParse(hdfContentId.Value, out id);
            if (txtSubject.Text + "" == "" || txtBody.Text + "" == "")
            {
                pnError.Visible = true;
                lblError.Text = "Bạn chưa nhập tiêu đề hoặc nôi dung. Vui lòng kiểm tra lại";
                pnSuccess.Visible = false;
                return;

            }
            else
            {
                if (scBUS.GetByName(id, txtSubject.Text, userLogin.UserId).Rows.Count > 0)
                {
                    pnError.Visible = true;
                    lblError.Text = "Trùng tên nội dung!";
                    pnSuccess.Visible = false;
                    return;

                }
            }
            int status = 1;//1-insert 2-update
            String ContentId = this.hdfContentId.Value.ToString();
            SendContentDTO scDTO = getscDTO();
            ConnectionData.OpenMyConnection();
            if (ContentId == "" || ContentId == null || int.Parse(ContentId) == 0)//them moi
            {
                scDTO.Id = scBUS.tblSendContent_insert(scDTO);
                hdfContentId.Value = scDTO.Id + "";
            }
            else
            {

                scBUS.tblSendContent_Update(scDTO);
                status = 2;

            }

            ConnectionData.CloseMyConnection();
            pnSuccess.Visible = true;

            if (status == 1)
            {
                lblSuccess.Text = "Bạn vừa thêm thành công một nội dung email !";
            }
            else
            {
                lblSuccess.Text = "Thông tin nội dung email đã được cập nhật !";
            }
            pnError.Visible = false;
            }
            catch (Exception ex)
            {
                common.Common.logs(userLogin.Username + " - CreateContentMail - Save", ex, Common.logType.error);
            }
        }

        private bool CheckNull()
        {

            string subject = "";
            string body = "";
            body = this.txtBody.Text.ToString();
            DateTime createdate = DateTime.Now;
            subject = this.txtSubject.Text.ToString();

            if (subject == "" || subject == null || body == null || body == "")
            {
                return false;
            }
            return true;
        }

        private SendContentDTO getscDTO()
        {
            UserLoginDTO userLogin = getUserLogin();
            SendContentDTO scDTO = new SendContentDTO();
            if (userLogin != null)
            {
                int id = 0;
                int.TryParse(this.hdfContentId.Value + "", out id);
                string subject = "";
                string body = "";
                body = this.txtBody.Text.ToString();
                DateTime createdate = DateTime.Now;
                subject = this.txtSubject.Text.ToString();
                scDTO.CreateDate = createdate;
                scDTO.Subject = subject;
                scDTO.Body = body;
                scDTO.Id = id;
                scDTO.userId = userLogin.UserId;
                scDTO.ContentType = Convert.ToInt32(ddlContentType.SelectedValue);
                return scDTO;
            }
            else
            {
                return null;
            }

        }
        private UserLoginDTO getUserLogin()
        {
            if (Session["us-login"] != null)
            {
                return (UserLoginDTO)Session["us-login"];
            }
            return null;
        }

        protected void resetForm()
        {
            txtSubject.Text = "";
            txtBody.Text = "";
            hdfContentId.Value = "";
            pnError.Visible = pnSuccess.Visible = false;
        }

        protected void btnRefesh_Click(object sender, EventArgs e)
        {
            resetForm();
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.RawUrl);
        }
        protected void lbtInsertSignature_Click(object sender, EventArgs e)
        {
            InitialBUS();
            try
            {
                int signId = int.Parse(((LinkButton)sender).CommandArgument.ToString());
                SignatureBUS signBus = new SignatureBUS();
                DataTable tblSign = signBus.GetById(signId);
                if (tblSign.Rows.Count > 0)
                {
                    txtBody.Text = txtBody.Text + "\n" + tblSign.Rows[0]["SignatureContent"].ToString();
                }
            }
            catch (Exception)
            {

                throw;
            }

        }
        protected void lbtEditSignature_Click(object sender, EventArgs e)
        {
            Response.Redirect("create-signature.aspx");
        }
        protected void lbtAddWelcome_Click(object sender, EventArgs e)
        {
            if (txtWelcome.Text != "" && txtAfterWelcome.Text != "")
            {

                String welcomeText = txtWelcome.Text;
                if (rdoCustomerName.Checked == true)
                {
                    welcomeText += " [khachhang] ";
                }
                else
                {
                    welcomeText += " [email] ";
                }
                welcomeText += txtAfterWelcome.Text;

                txtBody.Text = welcomeText + "</br>" + txtBody.Text;
            }
        }
        protected void btnPreview_Click(object sender, EventArgs e)
        {
            string ContentMail = this.txtBody.Text;
            Session["Content"] = ContentMail;
            //Response.Redirect("PreviewContent.aspx");

            ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('PreviewContent.aspx','_blank');", true);
        }


        [System.Web.Services.WebMethod]
        public static string GetCurrentTime(string name)
        {
            string selectedRdoValue = string.Empty;
            string selectedDdlValue = string.Empty;
            string selectedChkValue = string.Empty;
            Page page = HttpContext.Current.Handler as Page;
            TextBox txtBody = (TextBox)page.FindControl("txtBody");

            return "Hello " + name + Environment.NewLine + "The Current Time is: "
                + DateTime.Now.ToString();
        }

        #region Hàm xử lý javascript
        [System.Web.Services.WebMethod]
        public static string getContentTemplate(string contentId)
        {
            SendContentBUS scBUS = new SendContentBUS();
            int id = int.Parse(contentId);
            DataTable tblContent = scBUS.GetByID(id);
            if (tblContent.Rows.Count > 0)
            {
                return tblContent.Rows[0]["Body"].ToString();
            }
            return null;
        }
        [System.Web.Services.WebMethod]
        public static string getJsonSpam(string contentId)
        {
            // Lay noi dung cho xu ly spam.
            SendContentBUS scBUS = new SendContentBUS();
            int id = int.Parse(contentId);
            string contentDetail = null;
            DataTable tblContent = scBUS.GetByID(id);
            if (tblContent.Rows.Count > 0)
            {
                contentDetail = tblContent.Rows[0]["Body"].ToString();
            }

            // Tien hanh check spam
            SpamRuleBUS spamBUS = new SpamRuleBUS();
            DataTable spam = spamBUS.GetAll();

            List<SpamRuleDTO> listSpam = new List<SpamRuleDTO>();
            for (int i = 0; i < spam.Rows.Count; i++)
            {
                SpamRuleDTO spamDto = new SpamRuleDTO();
                spamDto.Keyword = spam.Rows[i]["Keyword"].ToString();
                spamDto.SameWord = spam.Rows[i]["SameWord"].ToString();
                spamDto.Score = float.Parse(spam.Rows[i]["Score"].ToString());
                listSpam.Add(spamDto);
            }

            var json = new JavaScriptSerializer().Serialize(listSpam);
            return json;

        }

        [System.Web.Services.WebMethod]
        public static string getSign(string SignId)
        {
            try
            {
                SignatureBUS signBus = new SignatureBUS();
                int id = int.Parse(SignId);
                DataTable tblSign = signBus.GetById(id);
                if (tblSign.Rows.Count > 0)
                {
                    return tblSign.Rows[0]["SignatureContent"].ToString();
                }
                return null;
            }
            catch (Exception)
            {
                throw;
            }
        }
        [System.Web.Services.WebMethod]
        public static string getJsonList(string content)
        {
            SpamRuleBUS spamBUS = new SpamRuleBUS();
            DataTable spam = spamBUS.GetAll();

            List<SpamRuleDTO> listSpam = new List<SpamRuleDTO>();
            for (int i = 0; i < spam.Rows.Count; i++)
            {
                SpamRuleDTO spamDto = new SpamRuleDTO();
                spamDto.Keyword = spam.Rows[i]["Keyword"].ToString();
                spamDto.SameWord = spam.Rows[i]["SameWord"].ToString();
                spamDto.Score = float.Parse(spam.Rows[i]["Score"].ToString());
                listSpam.Add(spamDto);
            }

            var json = new JavaScriptSerializer().Serialize(listSpam);
            return json;
        }

        [System.Web.Services.WebMethod]
        public static string Spam(string title, string content)
        {
            try
            {
                SpamRuleBUS spamBUS = new SpamRuleBUS();
                DataTable spam = spamBUS.GetAll();
                float totalScoreTitle = 0;
                float totalScoreContent = 0;
                string ruleContent = "";
                float ItemScore = 0;
                string key = "";
                string titleData = title;
                string contentData = HttpUtility.UrlDecode(content);
                #region MyRegion
                #region Fisrt
                ruleContent = "<div class='toolTipBox' style='padding: 5px; margin-top: 10px; background-color: rgb(224, 236, 255);" +
                        "color: rgb(51, 51, 51); text-decoration: none; margin-bottom: 15px; font-family: Tahoma, Arial;" +
                        "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                        "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                        "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                        "-webkit-text-stroke-width: 0px;'>" +
                        "<img align='left' height='16' src='../resource/images/infoballon.gif' width='20' />Thống" +
                        "kê nội dung các quy tắc vi phạm của &#39;<b>Tiêu đề gửi</b>&#39; chi tiết như bên" +
                        " dưới:</div>" +
                        "<div class='Heading2' style='font-weight: bold; color: rgb(0, 0, 0); height: 16pt;" +
                        "background-color: rgb(237, 236, 236); padding: 4px 4px 4px 10px; background-image: url(../resource/images/table_bg.gif);" +
                        "font-family: Tahoma, Arial; font-size: 11px; font-style: normal; font-variant: normal;" +
                        "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                        "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                        "-webkit-text-stroke-width: 0px;'>" +
                        "<div class='spamRuleBroken_row_rulename' style='float: left; padding: 3px 0px 3px 5px;'>" +
                        "Quy tắc vi phạm</div>" +
                        "<div class='spamRuleBroken_row_rulescore' style='float: right; width: 80px; text-align: right;" +
                        "padding: 3px 15px 3px 5px;'>" +
                        "Điểm</div>" +
                        "&nbsp;</div>" +
                        "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                       " display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                        "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                        "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                        "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                        "-webkit-text-stroke-width: 0px;'>";
                #endregion Fisrt
                foreach (DataRow RowItem in spam.Rows)
                {
                    key = " " + RowItem["Keyword"].ToString() + " ";
                    ItemScore = float.Parse(RowItem["Score"].ToString());
                    if (titleData.Contains(key) == true)
                    {
                        //Bắt đầu vòng lặp tính điểm tiêu đề
                        ruleContent += "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                              "display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                              "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                              "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                              "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                              "-webkit-text-stroke-width: 0px;'>";
                        ruleContent += "<div class='spamRuleBroken_row_rulename' style='float: left; padding: 3px 0px 3px 5px;'>" + "Chứa từ vi phạm '" + key + "'" + "</div>" +
                         "<div class='spamRuleBroken_row_rulescore' style='float: right; width: 80px; text-align: right;" + "padding: 3px 15px 3px 5px;'>" + ItemScore + "</div> </br>";
                        ruleContent += "</div>";
                        totalScoreTitle = totalScoreTitle + ItemScore;
                        // Kết thúc vòng lặp tính điểm tiêu đề
                    }
                }

                #region Medium
                ruleContent += "" +
                  "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                   "display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                   "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                   "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                   "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                   "-webkit-text-stroke-width: 0px;'>" +
                   "<div class='spamRuleBroken_graph' style='border: 1px solid gray; height: 5px; background-color: rgb(238, 238, 238);'>" +
                   "<div class='spam_notspam' style='background-color: rgb(0, 255, 0); height: 5px; width: 165.296875px;'>" +
                   "<img height='5' src='../resource/images/1x1.gif' width='1' /></div>" +
                   "</div>" +
                   "<div style='line-height: 1; margin-bottom: 5px;'>" +
                   "<br />" +
                   "Nội dung được đánh giá cao nhất<span class ='Apple-converted-space'>&nbsp;</span><span" +
                   " style='font-size: 12px; font-weight: bold;'><b>" + totalScoreTitle.ToString() + "</b></span><span class='Apple-converted-space'>&nbsp;</span>trong" +
                   " ngưỡng cho phép là 5. Điều này có nghĩa email của bạn sẽ được gửi đến đích, nhưng" +
                   "điều này không được bảo đảm tuyệt đối nó chỉ có giá trị tham khảo.</div>" +
                "</div>" +
                "<div class='toolTipBox' style='padding: 5px; margin-top: 10px; background-color: rgb(224, 236, 255);" +
                "color: rgb(51, 51, 51); text-decoration: none; margin-bottom: 15px; font-family: Tahoma, Arial;" +
                "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                "-webkit-text-stroke-width: 0px;'>" +
                "<img align='left' height='16' src='../resource/images/infoballon.gif' width='20' />Thống" +
                " kê nội dung các quy tắc vi phạm của &#39;<b>Nội dung gửi</b>&#39; chi tiết như" +
                " bên dưới:" + "</div>" +
                 "<div class='Heading2' style='font-weight: bold; color: rgb(0, 0, 0); height: 16pt;" +
                 "background-color: rgb(237, 236, 236); padding: 4px 4px 4px 10px; background-image: url(../resource/images/table_bg.gif);" +
                 "font-family: Tahoma, Arial; font-size: 11px; font-style: normal; font-variant: normal;" +
                 "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                 "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                 "-webkit-text-stroke-width: 0px;'>" +
                 "<div class='spamRuleBroken_row_rulename' style='float: left; padding: 3px 0px 3px 5px;'>" +
                 "Quy tắc vi phạm</div>" +
                 "<div class='spamRuleBroken_row_rulescore' style='float: right; width: 80px; text-align: right;" +
                 "padding: 3px 15px 3px 5px;'>" +
                 "Điểm</div>" +
                "&nbsp;</div>";

                #endregion
                //Đánh giá nội dung
                foreach (DataRow RowItem in spam.Rows)
                {
                    key = " " + RowItem["Keyword"].ToString() + " ";
                    ItemScore = float.Parse(RowItem["Score"].ToString());
                    if (contentData.Contains(key) == true)
                    {
                        //Bắt đầu vòng lặp tính điểm tiêu đề
                        ruleContent += "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                                     "display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                                     "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                                     "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                                     "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                                     "-webkit-text-stroke-width: 0px;'>";
                        ruleContent += "<div class='spamRuleBroken_row_rulename' style='float: left; padding: 3px 0px 3px 5px;'>" + "Chứa từ vi phạm '" + key + "'" + "</div>" +
                         "<div class='spamRuleBroken_row_rulescore' style='float: right; width: 80px; text-align: right;" + "padding: 3px 15px 3px 5px;'>" + ItemScore + "</div></br>";
                        ruleContent += "</div>";
                        totalScoreContent = totalScoreContent + ItemScore;
                        // Kết thúc vòng lặp tính điểm tiêu đề
                    }
                }

                //Kết thúc đánh giá nội dung
                #region End
                ruleContent += "" +
                  "<div class='spam_info spamRuleBroken_row' style='padding: 4px 8px; background-color: rgb(249, 249, 249);" +
                  "display: block; clear: both; color: rgb(103, 103, 103); font-family: Tahoma, Arial;" +
                  "font-size: 11px; font-style: normal; font-variant: normal; font-weight: normal;" +
                  "letter-spacing: normal; line-height: normal; orphans: auto; text-align: start;" +
                  "text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px;" +
                  "-webkit-text-stroke-width: 0px;'>" +
                  "<div class='spamRuleBroken_graph' style='border: 1px solid gray; height: 5px; background-color: rgb(238, 238, 238);'>" +
                  "<div class='spam_notspam' style='background-color: rgb(0, 255, 0); height: 5px; width: 50%;'>" +
                  "<img height='5' src='../../resource/images/1x1.gif' width='1' /></div>" + "</div>" +
                   "<div style='line-height: 1; margin-bottom: 5px;'>" + "<br />" +
                   "Nội dung được đánh giá cao nhất<span class='Apple-converted-space'>&nbsp;</span><span" +
                   " style='font-size: 13px; font-weight: bold;'>" + totalScoreContent.ToString() + "</span><span class='Apple-converted-space'>&nbsp;</span>trong" +
                   " ngưỡng cho phép là 5. Điều này có nghĩa email của bạn sẽ được gửi đến đích, nhưng" +
                   "điều này không được bảo đảm tuyệt đối nó chỉ có giá trị tham khảo." +
                    "</div>" +
                "</div>";
                #endregion
                #endregion
                return ruleContent;
            }
            catch (Exception)
            {
                return null;
            }

        }
        #endregion
    }

}